/**
 * Created by Administrator on 2017/6/10.
 */
var express = require('express');
var router = express.Router();

var UserToken = require('../db/user_tokens.js');
var paymentDao = require('../dao/payment.js');

var moment = require('moment');
var request = require('request');
var redis_short_link_db = require('../db/redis_short_link_db');
var paymentRouter = module.exports;

/**
 * 具体项目信息
 * @param  app_sid
 * @param  token
 * @param  vip_sid  可不传
 *         url/payment/filter
 */

paymentRouter.filter = function (req, res) {
    var par = req.body;
    UserToken.checkLogin(par.token, function(err, userInfo){
        if(err) {
            return;
        }
        if(!userInfo){
            res.json(new ERR('请先登录', 403));
            return ;
        }
        par.uid = userInfo.uid;
        if(!par.app_sid) return  res.json(new ERR('应用类型不能为空', 400));
        paymentDao.filter(par, function(e, d) {
            if(e) {
                res.json(new ERR(e, 400));
            } else {
                res.json(new PKG(d));
            }
        });
    });

}
router.post('/filter', paymentRouter.filter);

/** 用户购买权限
 * 具体项目信息
 * @param  id   (app_vip_item)
 * @param  token
 * @param  num   可不传  默认 1
 *         url/payment/costInfo
 */
paymentRouter.costInfo = function (req, res) {
    var par = req.body;
    UserToken.checkLogin(par.token, function(err, userInfo){
        if(err) {
            return;
        }
        if(!userInfo){
            res.json(new ERR('请先登录', 403));
            return ;
        }
        par.uid = userInfo.uid;
        if(par.num) {
           par.num = parseInt(par.num);
        } else {
            par.num = 1;
        }
        if(!par.id) return  res.json(new ERR('购买的会员类型不能为空', 400));
        paymentDao.costInfo(par, function(e, d) {
            if(e) {
                res.json(new ERR(e, 400));
            } else {
                res.json(new PKG(d));
            }
        });
    });

}
router.post('/costInfo', paymentRouter.costInfo);

/**
 * 订单生成
 * vip_type    0    购买会员类型
 * @param  token
 * @param  id            可购买项目的id
 * @param  total         总价
 * @param  num           份数
 * @param  avaiDay       可用天数
 * @param  expireDate    到期时间
 * @param  vip_type      类型
 *
 * vip_type    1     购买积分类型
 * @param  token
 * @param  id            可购买项目的id
 * @param  total         总价
 * @param  avaiScore     可用积分
 * @param  vip_type      类型
 *
 * vip_type    2     押金
 * @param  token
 * @param  id            可购买项目的id
 * @param  total         总价
 * @param  vip_type      类型
 *
 *
 * @param  isApp
 * @param  payType
 * @param  isMinPro
 * @param  openid
 * @param  code_type
 *
 * @param  isGzhPay     1  是公众号支付  不传或 0 则不是
 * @param  xqkVip       1  为向钱看vip   不传或 0 则不是
 * @param  offset       1  (使用余额抵消)|  0 (不使用余额抵消)
 *         url/payment/createOrder
 */

function filter(vip_type, par) {
    switch (parseInt(vip_type)) {
        case 0 :
        if(!par.id || (!par.offset && !par.total) || !par.avaiDay || !par.expireDate) {
            return false;
        } else {
            return true;
        }
        break;

        case 1 :
            if(!par.id || (!par.offset && !par.total) || !par.avaiScore ) {
                return false;
            } else {
                return true;
            }
        break;

        case 2 :
            if(!par.id || (!par.offset && !par.total) ) {
                return false;
            } else {
                return true;
            }
        break;

        default: return false;
    }
}

paymentRouter.createOrder = function (req, res) {
    var par = req.body;
    UserToken.checkLogin(par.token, function(err, userInfo){
        if(err) {
            res.json(new ERR(err, 400));
            return;
        }
        if(!userInfo){
            res.json(new ERR('请先登录', 403));
            return ;
        }
        if(par.vip_type == undefined) return  res.json(new ERR('购买类型不能为空', 400));
        if(par.num) {
            par.num = parseInt(par.num);
        } else {
            par.num = 1;
        }
        if(!filter(par.vip_type, par)) return  res.json(new ERR('购买信息不为空', 400));
        par.uid = userInfo.uid;

        paymentDao.createOrder(par, function(e, d) {
            if(e) {
                res.json(new ERR(e, 400));
            } else {
                if(par.isApp && par.payType == 'alipay') {
                    var req_url = getAppPayUrl(d, par);
                    if(par.offset && parseInt(par.offset) == 1) {
                        var payRes = {req_url: req_url, order_code:d.order_code};
                        if(d.pay_amount == 0) payRes.nopay = true;
                        res.json(new PKG(payRes));
                    } else {
                        res.json(new PKG(req_url));
                    }
                } else if(par.isMinPro && par.payType == 'wxpay') {
                    if(!par.openid) return res.json(new ERR('openid不为空！', 400));
                    getJSAPIPay(d, par, function(err, result) {
                        if(err) return res.json(new ERR(e, 400));
                        var obj = {
                            timeStamp: result.timeStamp,
                            nonceStr: result.nonceStr,
                            package: result.package,
                            signType: 'MD5',
                            paySign: result.paySign
                        };
                        res.json(new PKG(obj));
                    });
                } else if(par.isGzhPay && parseInt(par.isGzhPay) == 1 && par.xqkVip && parseInt(par.xqkVip) == 1) {
                    if(!par.openid) return res.json(new ERR('openid不为空！', 400));
                    xqkPay(d, par, function(err, result) {
                        if(err) return res.json(new ERR(e, 400));
                        res.json(new PKG(result));
                    })
                } else {
                    res.json(new PKG(d));
                }
            }
        });
    });
}
router.post('/createOrder', paymentRouter.createOrder);



//校验支付宝请求
var AlipayNotify={
    verity:function(params,callback){
        if(params.app_sid == 'usuz') {
            var AlipayConfig = require('../db/alipay_config.json').alipay_usuz_cfg;
            console.log('usuz');
        } else {
            var AlipayConfig = require('../db/alipay_config.json').alipay_cfg;
            console.log('other');
        }
        var myAppId = AlipayConfig.app_id;
        var appId = params["app_id"]?params["app_id"]:"";
        if(myAppId == appId){
            // console.log(myAppId);
            // console.log(appId);
            callback(true);
            // if(params["notify_id"]) {
            //
            //     var partner = AlipayConfig.partner;
            //     var veryfy_path = AlipayConfig.HTTPS_VERIFY_PATH + "partner=" + partner + "&notify_id=" + params["notify_id"];
            //
            //     requestUrl(AlipayConfig.ALIPAY_HOST1,veryfy_path,function(responseTxt){
            //         if(responseTxt){
            //             callback(true);
            //         }else{
            //             callback(false);
            //         }
            //     });
            // }
        } else{
            callback(false);
        }
        //日志部分
    }
};

var requestUrl=function(host,path,callback){
    var https = require('https');

    var options = {
        host: host,
        port: 443,
        path: path,
        method: 'GET'
    };

    var req = https.request(options, function(res) {
        res.on('data', function(d) {
            callback(d);
        });
    });
    req.end();
    req.on('error', function(e) {
        console.error(e);
    });
};

/**
 * 支付宝支付 (当面付)
 * @param  token
 * @param  orderCode  订单号
 *         url/payment/aliPayTo
 */
paymentRouter.aliPayTo = function (req, res) {
    var par = req.body;
    if(!par.token) {
        return res.json(new ERR('token 不为空！', 400));
    }
    UserToken.checkLogin(par.token, function(err, userInfo){
        if(err) {
            return;
        }
        if(!userInfo){
            res.json(new ERR('请先登录', 403));
            return ;
        }
        if(!par.orderCode) return  res.json(new ERR('订单号码不能为空', 400));
        paymentDao.getOrderInfo(par, function(e, d){
            if(e) {
                res.json(new ERR(e, 400));
            } else {
                if(d.app_sid == 'usuz') {
                    var AlipayConfig = require('../db/alipay_config.json').alipay_usuz_cfg;
                    var alib = require('../libs/alipay_usuz/alipay.js');
                } else {
                    var AlipayConfig = require('../db/alipay_config.json').alipay_cfg;
                    var alib = require('../libs/alipay/alipay.js');
                }
                var out_trade_no = d.order_code;
                var subject = d.vip_name;
                var body = d.vip_name;
                var total_fee = d.pay_amount;
                // var total_fee = 0.01;
                var app_id = AlipayConfig.app_id;
                var method = "alipay.trade.precreate";
                var charset = AlipayConfig.input_charset;
                var sign_type = "RSA";
                var timestamp = moment().format("YYYY-MM-DD HH:mm:ss");
                var format = "json";
                var version = "1.0";
                var biz_content = {
                    out_trade_no : out_trade_no,
                    total_amount : total_fee,
                    subject : subject,
                    timeout_express : "10m",
                    body : body
                };

                var sParaTemp = [];
                sParaTemp.push(["app_id", app_id]);
                sParaTemp.push(["method", method]);
                sParaTemp.push(["charset", charset]);
                sParaTemp.push(["sign_type", sign_type]);
                sParaTemp.push(["timestamp", timestamp]);
                sParaTemp.push(["format", format]);
                sParaTemp.push(["version", version]);
                sParaTemp.push(["notify_url", AlipayConfig.notify_url]);
                sParaTemp.push(["biz_content", JSON.stringify(biz_content)]);
                // sParaTemp.push(["business_params", JSON.stringify({name:'hello'})]);

                var sPara = alib.buildRequestPara2(sParaTemp);

                var path = AlipayConfig.ALIPAY_PATH;

                var sURL = alib.getPath(path, sPara);
                //console.log('sURL', "https://openapi.alipay.com/"+sURL);

                request({
                    url: AlipayConfig.ali_host + sURL,
                    // url: AlipayConfig.test_host + sURL,
                    method: 'GET',
                    headers: {
                        'charset': 'utf-8'
                    }
                },function(error, response, body){
                    console.log("支付宝返回内容:\n", body);

                    body = JSON.parse(body);
                    var result = alib.checkRSA(body.alipay_trade_precreate_response, body.sign);
                    var response = body.alipay_trade_precreate_response;

                    var qr_img = "";
                    if(response.code !== "10000"){
                        qr_img = "";
                    } else {
                        qr_img = 'http://qr.liantu.com/api.php?&w=200&text='+response.qr_code;
                    }
                    res.json({qr_img: qr_img, order_code: par.orderCode});
                });
            }
        });
    });
}
router.post('/aliPayTo', paymentRouter.aliPayTo);

/**
 * 支付宝支付 (app支付)
 */
function getAppPayUrl(data, par) {
    if(par.payType == 'alipay') {
        if(data.app_sid == 'usuz') {
            var AlipayConfig = require('../db/alipay_config.json').alipay_usuz_cfg;
            var alib = require('../libs/alipay_usuz/alipay.js');
        } else {
            var AlipayConfig = require('../db/alipay_config.json').alipay_cfg;
            var alib = require('../libs/alipay/alipay.js');
        }
        var out_trade_no = data.order_code;
        var subject = data.vip_name;
        var body = data.vip_name;
        console.log(data.pay_amount);
        var total_fee = parseFloat(parseFloat(data.pay_amount).toFixed(2));
        // var total_fee = 0.01;
        var app_id = AlipayConfig.app_id;
        var method = "alipay.trade.app.pay";
        var charset = AlipayConfig.input_charset;
        var sign_type = "RSA";
        var timestamp = moment().format("YYYY-MM-DD HH:mm:ss");
        var format = "json";
        var version = "1.0";
        var biz_content = {
            out_trade_no : out_trade_no,
            total_amount : total_fee,
            subject : subject,
            timeout_express : "10m",
            body : body
        };
        var sParaTemp = [];
        sParaTemp.push(["app_id", app_id]);
        sParaTemp.push(["method", method]);
        sParaTemp.push(["charset", charset]);
        sParaTemp.push(["sign_type", sign_type]);
        sParaTemp.push(["timestamp", timestamp]);
        sParaTemp.push(["format", format]);
        sParaTemp.push(["version", version]);
        sParaTemp.push(["notify_url", AlipayConfig.notify_url]);
        sParaTemp.push(["biz_content", JSON.stringify(biz_content)]);

        var sPara = alib.buildRequestPara2(sParaTemp);

        var path = AlipayConfig.ALIPAY_PATH;

        var sURL = alib.getPath(path, sPara);
        sURL = sURL.replace('gateway.do?','');
        return sURL;
    }
}

/**
 * 小程序支付
 */
function getJSAPIPay(d, par, cb) {
    var input = new PayData.WxPayDataBase();
    var out_trade_no = d.order_code;
    var total_fee = parseInt(d.pay_amount * 100);
    // var total_fee = 1;
    var body = d.vip_name;
    var qrUrl = '';
    var payApi = new API.WxPayApi();
    input.SetBody(body);                                             //商品描述
    input.SetAttach(d.vip_name);                                     //附加信息
    input.SetOut_trade_no(out_trade_no);                             //订单号
    input.SetTotal_fee(total_fee);                                   //价格  单位分
    // input.SetNotify_url("http://sk92cm.natappfree.cc/qrcode/notify");//回调地址
    input.SetSpbill_create_ip('127.0.0.1');                          //终端ip
    if(par.isMinPro) {
        input.SetTrade_type("JSAPI");
        input.SetOpenid(par.openid);
    } else {
        input.SetTrade_type("NATIVE");      //交易类型  扫码 （native） 公众号（jsapi）  app  MWEB
    }
    input.SetProduct_id(d.vip_name);                                 //商品id   native  必传
    input.SetKeys();
    // var ip = req.get("X-Real-IP") || req.get("X-Forwarded-For") || req.ip;
    var ip = '127.0.0.1';
    if(input.GetTrade_type() == 'NATIVE') {
        payApi.unifiedOrder(input, 6, null, ip, function(result){
            if(result) {
                result = input.Init(result);
                qrUrl = result['code_url'];
                cb(null, {qrUrl:qrUrl});
            } else {
                cb('生成二维码失败！');
            }
        });
    } else if(input.GetTrade_type() == 'JSAPI') {
        var canSwitch = ( par.code_type && par.code_type == 'duoke_program') ? true : false;
        payApi.unifiedOrder(input, 6, canSwitch, ip, function(result){
            if(result) {
                result = input.Init(result);
                if(result.return_code == 'SUCCESS') {
                    var obj = {nonceStr: result.nonce_str, package:'prepay_id='+result.prepay_id, timeStamp: new Date().getTime().toString()};
                    var paySign = input.MakePaySign(obj, canSwitch);
                    obj.paySign = paySign;
                    cb(null, obj);
                } else {
                    cb('订单生成失败， 请重试！');
                }
            } else {
                cb('参数有误！');
            }
        });
    }
}

/**
 * 向前看支付
 */
function xqkPay(d, par, cb) {
    var wx_config = require('../db/wx_pay_config.json');
    var input = new dynamicWxPayData.WxPayDataBase();
    var out_trade_no = d.order_code;
    var total_fee = parseInt(d.pay_amount * 100);
    var body = d.vip_name;
    var payApi = new dynamicWxApi.WxPayApi();
    par.ip = '127.0.0.1';
    input.SetBody(body);                                             //商品描述
    input.SetAttach(d.vip_name);                                     //附加信息
    input.SetOut_trade_no(out_trade_no);                             //订单号
    input.SetTotal_fee(total_fee);                                   //价格  单位分

    input.SetNotify_url(wx_config.usuz.NOTIFY_URL);                  //回调地址
    input.SetSpbill_create_ip(par.ip);                               //终端ip
    input.SetTrade_type("JSAPI");
    input.SetOpenid(par.openid);
    input.SetProduct_id(d.vip_name);                                 //商品id   native  必传
    input.SetKeys();
    payApi.unifiedOrder(input, 6, wx_config.usuz, par.ip, function(result){
        result = input.Init(result);
        if(result.return_code == 'SUCCESS') {
            var obj = {nonceStr: result.nonce_str, package:'prepay_id='+result.prepay_id, timeStamp: new Date().getTime().toString()};
            var paySign = input.MakePaySign(obj, wx_config.usuz);
            obj.paySign = paySign.toUpperCase();
            obj.signType = 'MD5';
            obj.appId = wx_config.usuz.APPID;
            cb(null, obj);
        } else {
            console.log(result);
            cb('订单生成失败， 请重试！');
        }
    });
}
/**
 * 支付
 * @param  out_trade_no  订单号
 *         url/payment/test
 */
paymentRouter.test = function(req, res) {
    var params = req.body;
    params.status = '13';
    params.payment = 'alipay';
    params.pay_type = 'f2f';
    paymentDao.tradeSuccess(params, function(e) {
        if(e) {
            console.log(e);
            res.json(new ERR(e, 400));
            return;
        } else {
            console.log('success');
            res.json(new PKG('success'));
        }
    });
}
router.post('/test', paymentRouter.test);

/**
 * 支付宝 回调
 * @param
 *         url/payment/paynotify
 */
paymentRouter.paynotify = function (req, res) {
    var params = req.body;
    var trade_status = params.trade_status;
    paymentDao.getAppsid(params, function(err, data){
        if(err) {
            console.log(err);
            return res.end("fail");
        } else {
            params.app_sid = data.app_sid;
            AlipayNotify.verity(params,function(result){
                if(result){
                    if (trade_status=="TRADE_SUCCESS") {
                        params.status = '13';
                        params.payment = 'alipay';
                        params.pay_type = 'f2f';
                        paymentDao.tradeSuccess(params, function(e) {
                            if(e) {
                                console.log(e);
                                return;
                            } else {
                                console.log('success');
                            }
                        });
                    }
                    res.end("success");
                } else{
                    res.end("fail");
                }
            });
        }
    })

}
router.post('/paynotify', paymentRouter.paynotify);

/**
 * 支付宝 回调
 * @param
 *         url/payment/payreturn
 */
paymentRouter.payreturn = function (req, res) {
    var params = req.query;
    var trade_status = params.trade_status;
    paymentDao.getAppsid(params, function(err, data){
        if(err) {
            console.log(err);
            return res.end("fail");
        } else {
            params.app_sid = data.app_sid;
            AlipayNotify.verity(params,function(result){
                if(result){
                    if (trade_status=="TRADE_SUCCESS") {
                        params.status = '13';
                        params.payment = 'alipay';
                        params.pay_type = 'f2f';
                        paymentDao.tradeSuccess(params, function(e) {
                            if(e) {
                                console.log(e);
                                return;
                            } else {
                                console.log('success');
                            }
                        });
                    }
                    res.end("success");
                } else{
                    res.end("fail");
                }
            });
        }
    });
}
router.get('/payreturn', paymentRouter.payreturn);

/**
 * 轮询  支付状态  （当支付成功后返回给前端）
 * @param  token
 * @param  orderCode
 *         url/payment/polling
 */
paymentRouter.polling = function (req, res){
    var par = req.body;
    if(!par.token) {
        return res.json(new ERR('token 不为空！', 400));
    }
    UserToken.checkLogin(par.token, function(err, userInfo){
        if(err) {
            return;
        }
        if(!userInfo){
            res.json(new ERR('请先登录', 403));
            return ;
        }
        if(!par.orderCode) return  res.json(new ERR('订单号码不能为空', 400));
        par.uid = userInfo.uid;
        paymentDao.polling(par,function(e, d) {
            if(e) {
                res.json(new ERR(e, 400));
            } else {
                if(d.status == '13') {
                    res.json(new PKG());
                } else {
                    res.json(new ERR('未付款', 400));
                }
            }
        });
    });
}
router.post('/polling', paymentRouter.polling);

//微信支付

var API = require('../libs/wxpay/WxPayApi.js');
var PayData = require('../libs/wxpay/WxPayDatabak.js');

/**
 * 微信支付
 * @param  token
 * @param  orderCode
 * @param  isWebPay     1 | 0
 *         url/payment/wxPayTo
 */
paymentRouter.wxPayTo = function (req, res) {
    var par = req.body;
    if(!par.token) {
        return res.json(new ERR('token 不为空！', 400));
    }
    var ip = req.get("X-Forwarded-For") ? req.get("X-Forwarded-For").split(',')[0] : '127.0.0.1';
    ip = getIp4(ip);
    UserToken.checkLogin(par.token, function(err, userInfo){
        if(err) {
            return;
        }
        if(!userInfo){
            res.json(new ERR('请先登录', 403));
            return ;
        }
        if(!par.orderCode) return  res.json(new ERR('订单号码不能为空', 400));
        paymentDao.getOrderInfo(par, function(e, d){
            if(e) {
                res.json(new ERR(e, 400));
            } else {
                var input = new PayData.WxPayDataBase();
                var out_trade_no = d.order_code;
                var total_fee = parseInt(d.pay_amount * 100);
                // var total_fee = 1;
                var body = d.vip_name;
                var qrUrl = '';
                var payApi = new API.WxPayApi();
                input.SetBody(body);                                             //商品描述
                input.SetAttach(d.vip_name);                                     //附加信息
                input.SetOut_trade_no(out_trade_no);                             //订单号
                input.SetTotal_fee(total_fee);                                   //价格  单位分
                // input.SetNotify_url("https://www.pduoke.com/uc/payment/");    //回调地址
                input.SetSpbill_create_ip(ip);                                   //终端ip
                if(par.isMinPro) {
                    input.SetTrade_type("JSAPI");
                    input.SetOpenid(par.openid);
                } else if(parseInt(par.isWebPay) == 1) {
                    input.SetTrade_type("MWEB");
                } else {
                    input.SetTrade_type("NATIVE");                               //交易类型  扫码 （native） 公众号（jsapi）app
                }
                input.SetProduct_id(d.vip_name);                                 //商品id   native  必传
                input.SetKeys();
                if(input.GetTrade_type() == 'NATIVE') {
                    payApi.unifiedOrder(input, 6, null, ip, function(result){
                        if(result) {
                            result = input.Init(result);
                            qrUrl = result['code_url'];
                            console.log(result);
                            res.json(new PKG({qrUrl:qrUrl}));
                        } else {
                            res.json(new ERR('生成二维码失败！', 400));
                        }

                    });
                } else if(input.GetTrade_type() == 'MWEB') {
                    payApi.unifiedOrder(input, 6, null, ip, function(result){
                        if(result) {
                            console.log(result);
                            result = input.Init(result);
                            res.json(new PKG({mweb_url:result.mweb_url}));
                        } else {
                            res.json(new ERR('支付时发生错误,请重试！', 400));
                        }
                    });
                }
            }
        });
    });
}
router.post('/wxPayTo', paymentRouter.wxPayTo);


/**
 * 微信支付成功 回调
 * @param
 *         url/payment/wxPayNotify
 */
function wxNotify(req, res, key) {
    if(!key) key = 'NUrEhlxCN46exj4boHUfi0QNvCXAIjiE';
    var parseString = require('xml2js').parseString;
    parseString(req.rawBody, {explicitArray : false},function (err, result) {
        var notify = result.xml;
        var response = {
            return_code:"",
            return_msg:""
        };
        var input = new PayData.WxPayDataBase();
        var sign = input.IsWxReturn(notify, key);
        if(sign != notify.sign) {
            response={
                return_code:"FAIL",
                return_msg:notify.return_msg
            }
        } else if(notify.return_code == "SUCCESS" && notify.result_code =="SUCCESS"){
            var par = {};
            par.status = '13';
            par.payment = 'wxpay';
            par.pay_type = 'f2f';
            par.out_trade_no = notify.out_trade_no;
            paymentDao.tradeSuccess(par, function(e) {
                if(e) {
                    console.log(e);
                    return;
                } else {
                    console.log('success');
                }
            });
            response={
                return_code:"SUCCESS",
                return_msg:"OK"
            }
        } else {
            response={
                return_code:"FAIL",
                return_msg:notify.return_msg
            }
        }
        var resXML = '<xml><return_code><![CDATA['+response.return_code+']]></return_code> <return_msg><![CDATA['+response.return_msg+']]></return_msg> </xml>';
        res.send(resXML);
        res.end(resXML);
    });
}
paymentRouter.wxPayNotify = function (req, res) {
    wxNotify(req, res);
}
router.post('/wxPayNotify', paymentRouter.wxPayNotify);

/**
 * 微信支付成功 回调  (xqk)
 * @param
 *         url/payment/xqkNotify
 */
paymentRouter.xqkNotify = function (req, res) {
    var wx_config = require('../db/wx_pay_config.json');
    wxNotify(req, res, wx_config.usuz.KEY);
}
router.post('/xqkNotify', paymentRouter.xqkNotify);


/** 管理员为用户添加权限
 * 具体项目信息
 * @param  id   (app_vip_item)
 * @param  token
 * @param  uid
 * @param  num
 * @param  app_sid
 *         url/payment/admAddVipToUser
 */
paymentRouter.admAddVipToUser = function(req, res){
    var par = req.body;
    UserToken.checkLogin(par.token, function(err, adminInfo){
        if(err) {
            res.json(new ERR('请先登录', 403));
            return;
        }
        if(!adminInfo){
            res.json(new ERR('请先登录', 403));
            return ;
        }
        if(!adminInfo.isAdmin){
            res.json(new ERR('无权限', 400));
            return ;
        }
        if(!par.app_sid){
            res.json(new ERR('项目类型不能为空', 400));
            return ;
        }
        if(adminInfo.role.indexOf('admin') < 0 && adminInfo.role.indexOf('adm_'+par.app_sid) < 0){
            res.json(new ERR('无权限', 400));
            return;
        }

        if(!par.uid){
            res.json(new ERR('uid不为空！', 400));
            return ;
        }
        if(par.num) {
            par.num = parseInt(par.num);
        } else {
            par.num = 1;
        }
        if(!par.id) return  res.json(new ERR('购买的会员类型不能为空', 400));

        paymentDao.costInfo(par, function(e, d) {
            if(e) {
                res.json(new ERR(e, 400));
            } else {
                res.json(new PKG(d));
            }
        });
    });
}
router.post('/admAddVipToUser', paymentRouter.admAddVipToUser);

/** 一天试用接口
 * @param  token
 * @param  app_sid
 *         url/payment/trialOneDay
 */
paymentRouter.trialOneDay = function(req, res) {
    var par = req.body;
    if(!par.token) return res.json(new ERR('token不为空！', 400));
    if(!par.app_sid) return res.json(new ERR('app_sid不为空！', 400));
    UserToken.checkLogin(par.token, function(err, userInfo){
        if(err) {
            res.json(new ERR('请先登录', 403));
            return;
        }
        if(!userInfo){
            res.json(new ERR('请先登录', 403));
            return ;
        }
        par.uid = userInfo.uid;
        par.account = userInfo.account;
        paymentDao.trialOneDay(par, function(err, data){
            if(err) {
                res.json(new ERR(err, 400));
            } else {
                res.json(new PKG(data));
            }
        });
    });
}
router.post('/trialOneDay', paymentRouter.trialOneDay);

/** 商城兑换接口
 * @param  token
 * @param  app_key
 * @param  app_sign
 * @param  app_time
 * @param  sum
 * @param  order_code
 * @param  uid
 * @param  v
 *         url/payment/shopExchange
 */
paymentRouter.shopExchange = function(req, res) {
    var par = req.body;
    if(!par.token) return res.json(new ERR('token不为空！', 400));
    if (!par.app_key) return res.json(new ERR('产品key不为空', 400));
    if (!par.app_sign) return res.json(new ERR('产品sign不为空', 400));
    if (!par.app_time) return res.json(new ERR('产品时间戳不为空', 400));
    if (!checkSrvConnection(par)) return res.json(new ERR('无访问权限', 400));
    UserToken.checkLogin(par.token, function(err, userInfo){
        if(!par.sum) return res.json(new ERR('sum不为空！', 400));
        if(!par.order_code) return res.json(new ERR('order_code不为空！', 400));
        if(!par.uid) return res.json(new ERR('uid不为空！', 400));
        if (!par.v) return res.json(new ERR('v不为空', 400));
        if(err) {
            res.json(new ERR('请先登录', 403));
            return;
        }
        if(!userInfo){
            res.json(new ERR('请先登录', 403));
            return ;
        }
        if(par.uid != userInfo.uid) return res.json(new ERR('无访问权限', 400));
        // res.json(new PKG('success'));
        paymentDao.shopExchange(par, function(err, data){
            if(err) {
                res.json(new ERR(err, 400));
            } else {
                res.json(new PKG('success'));
            }
        });
    });
}
router.post('/shopExchange', paymentRouter.shopExchange);


/**
 * @param  token
 * @param  order_code
 * @param  app_sid
 *         url/payment/RecoveryMoney
 */
paymentRouter.recoveryMoney = function(req, res) {
    var par = req.body;
    if (!par.token) return res.json(new ERR('token不为空！', 400));
    if (!par.order_code) return res.json(new ERR('订单编号不为空', 400));
    if (!par.app_sid) return res.json(new ERR('app_sid不为空', 400));
    UserToken.checkLogin(par.token, function(err, userInfo){
        if(err) return res.json(new ERR(err, 403));
        par.uid = userInfo.uid;
        paymentDao.recoveryMoney(par, function(err){
            if(err) {
                res.json(new ERR(err, 400));
            } else {
                res.json(new PKG('success'));
            }
        });
    });
}
router.post('/recoveryMoney', paymentRouter.recoveryMoney);

/**
 * @param  token
 * @param  order_code
 * @param  app_sid
 *         url/payment/RecoveryMoney
 */
paymentRouter.recoveryMoneyBySrv = function(req, res) {
    var par = req.body;
    if (!par.app_key) return res.json(new ERR('产品key不为空', 400));
    if (!par.app_sign) return res.json(new ERR('产品sign不为空', 400));
    if (!par.app_time) return res.json(new ERR('产品时间戳不为空', 400));
    if (!checkSrvConnection(par)) return res.json(new ERR('无访问权限', 400));
    if (!par.order_code) return res.json(new ERR('订单编号不为空', 400));
    if (!par.app_sid) return res.json(new ERR('app_sid不为空', 400));
    if (!par.uid) return res.json(new ERR('uid不为空', 400));
    paymentDao.recoveryMoney(par, function(err){
        if(err) {
            res.json(new ERR(err, 400));
        } else {
            res.json(new PKG('success'));
        }
    });
}
router.post('/recoveryMoneyBySrv', paymentRouter.recoveryMoneyBySrv);

/**
 * 微信     wxpay      (partner)
 * @param   subject              订单标题
 * @param   total_amount         交易金额
 * @param   body                 商品描述
 * @param   name                 身份
 * @param   t                    时间戳
 * @param   sign                 签名
 * @param   partner_no           合作方自定义订单号
 * @param   url                  回调url
 * @param   pay_type             scan
 *         url/payment/wxPay
 */
var dynamicWxApi = require('../libs/dynamic_wxpay/WxPayApi');
var dynamicWxPayData = require('../libs/dynamic_wxpay/WxPayData');
var wxConfig = require('../db/wxpay_config.json');
function getOutTradeNo(id) {
    var now = new Date();
    var code = '' + id + now.getFullYear() + parseInt(now.getMonth() + 1) + now.getDate() + now.getHours() + now.getMinutes() + now.getSeconds() + Math.floor(Math.random()*10) + Math.floor(Math.random()*10) + Math.floor(Math.random()*10) + Math.floor(Math.random()*10) + Math.floor(Math.random()*10) + Math.floor(Math.random()*10) + now.getMilliseconds();
    return code + '1515';
}
function getWxConfig(data, cb) {
    redis_short_link_db.get(wxConfig.redisKey, function(err, result) {
        if(err) return cb('服务器异常101，请重新访问！');
        if(result) {
            try {
                var wxAccs = JSON.parse(result);
                var wxPool = [];
                var today = new Date().getDate();
                for(var k in wxAccs) {
                    var money = 0;
                    if(k != 'updateDay' && wxAccs[k] && wxAccs.updateDay == today) {
                        money = parseFloat(wxAccs[k].money);
                    }
                    if(k != 'updateDay' && wxConfig.wxAccs[k].limitMoney > (money + parseFloat(data.total_amount)).toFixed(2)) {
                        wxPool.push(k);
                    }
                }
                if(wxPool.length <= 0) return cb('抱歉，已达当日限额，请联系客服！');
                cb(null, wxConfig.wxAccs[wxPool[Math.floor(Math.random()*wxPool.length)]]);
            } catch(e) {
                console.log(e);
                cb('服务器异常102，请重新访问！');
                return;
            }
        } else {
            var wxPool = [];
            for(var k in wxConfig.wxAccs) wxPool.push(wxConfig.wxAccs[k]);
            cb(null, wxPool[Math.floor(Math.random()*wxPool.length)]);
        }
    })
}
function wxPay(par, res) {
    if(!par.total_amount)  return  res.json(new  ERR('交易金额不为空！',  400));
    if(!par.subject)  return  res.json(new  ERR('订单标题不为空！',  400));
    if(!par.body)  return  res.json(new  ERR('商品描述不为空！',  400));
    if(!par.partner_no)  return  res.json(new  ERR('自定义订单号不为空！',  400));
    if(isNaN(par.total_amount))  return  res.json(new  ERR('交易金额格式错误！',  400));
    if(parseFloat(par.total_amount)  <  0.01)  return  res.json('交易金额太小，请修改交易金额',  400);
    if(!par.name)  return  res.json(new  ERR('名称不为空！',  400));
    if(!par.t)  return  res.json(new  ERR('时间戳不为空！',  400));
    if(!par.sign)  return  res.json(new  ERR('签名不为空！',  400));
    if(!par.url)  return  res.json(new  ERR('回调地址不为空！',  400));
    if(!checkOvertime(par.t)) return res.json(new ERR('访问超时，请重新访问！', 400));
    getWxConfig(par, function(err, wx_config) {
        if(err) return res.json(new ERR(err, 400));
        paymentDao.getPartnerInfo(par.name,  function(e,  d)  {
            if(e)  return  res.json(new  ERR(e,  400));
            if(!checkPartnerSign(d.secret,  par))  return  res.json(new  ERR('签名错误！',  400));
            par.pi_id  =  d.id;
            var input = new dynamicWxPayData.WxPayDataBase();
            var out_trade_no = getOutTradeNo(par.pi_id);
            var total_fee = parseInt(par.total_amount * 100);
            var payApi = new dynamicWxApi.WxPayApi();
            input.SetBody(par.body);
            input.SetAttach(par.subject);
            input.SetOut_trade_no(out_trade_no);
            input.SetTotal_fee(total_fee);
            input.SetSpbill_create_ip(par.ip);
            input.SetNotify_url(wx_config.NOTIFY_URL);
            if(par.pay_type && par.pay_type == 'scan') {
                input.SetTrade_type("NATIVE");
            } else {
                input.SetTrade_type("MWEB");
            }
            input.SetProduct_id(par.subject);
            input.SetKeys();

            var  orderInfo  =  {
                out_trade_no: out_trade_no,
                total_amount: par.total_amount,
                subject: par.subject,
                body: par.body,
                pi_id: par.pi_id,
                partner_no: par.partner_no,
                url: par.url
            };

            paymentDao.saveCustomOrder(orderInfo, function(err, data) {
                if(err) {
                    res.json(new ERR(err, 400));
                } else {
                    var err = '';
                    if( par.pay_type && par.pay_type == 'scan') {
                        err = '生成二维码失败,请重试！';
                    } else {
                        err = '生成h5支付url失败,请重试！';
                    }
                    payApi.unifiedOrder(input, 6, wx_config, par.ip, function(result){
                        if(result) {
                            result = input.Init(result);
                            if(par.pay_type && par.pay_type == 'scan') {
                                orderInfo.qr_img = result.code_url;
                                return res.json(new PKG(orderInfo));
                            } else {
                                orderInfo.url = result.mweb_url;
                                var str = 'wx' + data;
                                redis_short_link_db.set(str, orderInfo.url, 180, function(e, result) {
                                    if(e) console.log(e);
                                    orderInfo.url = 'https://www.pduoke.com/wxPay.html?id=' + data;
                                    return res.json(new PKG(orderInfo));
                                })
                            }
                        } else {
                            res.json(new ERR(err, 400));
                        }
                    });
                }
            });
        });
    })
}
paymentRouter.wxPay = function(req, res) {
    var par = req.body;
    var ip = req.get("X-Forwarded-For");
    if(ip && ip.indexOf(',')) {
        ip = ip.split(',')[0];
    } else {
        ip = '127.0.0.1';
    }
    par.ip = getIp4(ip);
    wxPay(par, res);
}
router.post('/wxPay', paymentRouter.wxPay);

/**
 * 微信     wxpay      (partner)
 *         url/payment/wxPay2Notify
 */
function updateWxMoney(data, cb) {
    redis_short_link_db.get(wxConfig.redisKey, function(err, result) {
        if(err) return cb('服务器异常101，请重新访问！');
        var today = new Date().getDate();
        if(result) {
            var wxAccInfo = JSON.parse(result);
            if(wxAccInfo.updateDay != today) {
                for (var k in wxAccInfo) {
                    if(k != 'updateDay') {
                        wxAccInfo[k].money = 0;
                        wxAccInfo[k].money = (wxConfig.wxAccs[k] && wxConfig.wxAccs[k].MCHID == data.mch_id) ? parseFloat(data.total_amount).toFixed(2) : 0;
                    }
                }
                wxAccInfo.updateDay = today;
            } else {
                for (var k in wxAccInfo) {
                    if(k != 'updateDay') {
                        wxAccInfo[k].money = (wxConfig.wxAccs[k] && wxConfig.wxAccs[k].MCHID == data.mch_id) ? (parseFloat(data.total_amount) + parseFloat(wxAccInfo[k].money)).toFixed(2) : wxAccInfo[k].money ? wxAccInfo[k].money : 0;
                    }
                }
                console.log(wxAccInfo);
            }
        } else {
            var wxAccInfo = {};
            wxAccInfo.updateDay = today;
            for(var k in wxConfig.wxAccs) {
                wxAccInfo[k] = {}
                if(wxConfig.wxAccs[k].MCHID == data.mch_id) {
                    wxAccInfo[k].money = data.total_amount;
                } else {
                    wxAccInfo[k].money = 0;
                }
            }
        }
        redis_short_link_db.set(wxConfig.redisKey, JSON.stringify(wxAccInfo), 0, function(err) {
            if (err) {
                cb('服务器异常203，请稍候再试');
                return;
            }
            cb(null, null)
        })
    })
}
paymentRouter.wxPay2Notify = function (req, res) {
    var parseString = require('xml2js').parseString;
    parseString(req.rawBody, {explicitArray : false},function (err, result) {
        var notify = result.xml;
        var response = {
            return_code:"",
            return_msg:""
        };
        if(notify.return_code == "SUCCESS" && notify.result_code =="SUCCESS"){
            console.log(notify);
            var par = {};
            par.status = '1';
            par.out_trade_no = notify.out_trade_no;
            par.trade_no = notify.transaction_id;
            par.total_amount = notify.total_fee / 100;
            updateWxMoney({total_amount: par.total_amount, mch_id: notify.mch_id}, function() {});
            paymentDao.partnerTradeSuccess(par, function(e) {
                if(e) {
                    console.log(e);
                    return;
                } else {
                    console.log('success');
                }
            });
            response={
                return_code:"SUCCESS",
                return_msg:"OK"
            }

        } else {
            response={
                return_code:"FAIL",
                return_msg:notify.return_msg
            }
        }
        var resXML = '<xml><return_code><![CDATA['+response.return_code+']]></return_code> <return_msg><![CDATA['+response.return_msg+']]></return_msg> </xml>';
        res.send(resXML);

        res.end(resXML);
    });
}
router.post('/wxPay2Notify', paymentRouter.wxPay2Notify);

/**
 * 微信   (partner)         短链接跳转
 * @param   id
 *          url/payment/wxShortLink
 */
paymentRouter.wxShortLink = function (req, res) {
    var par = req.query;
    if(!par.id) return res.json(new ERR('短链接不为空！', 400));
    par.id = 'wx' + par.id;
    redis_short_link_db.get(par.id, function(err, result) {
        if(err || result == null) {
            return res.json(new ERR('该链接为不合法', 400));
        }
        res.json(new PKG(result));
    })
}
router.get('/wxShortLink', paymentRouter.wxShortLink);

/**
 * 微信     (llc)
 *          url/payment/llcPay
 */
paymentRouter.llcPay = function (req, res) {
    var par = req.body;
    var ip = req.get("X-Forwarded-For");
    if(ip && ip.indexOf(',')) {
        ip = ip.split(',')[0];
    } else {
        ip = '127.0.0.1';
    }
    par.ip = getIp4(ip);
    par.total_amount = Math.ceil(Math.random()*100);
    if(par.total_amount <= 0) par.total_amount = 100;
    par.name = 'llc';
    par.t = new Date().getTime();
    par.subject = '微淘客合作商户收款';
    par.body = '微淘客合作商户收款';
    par.partner_no = 'llc' + getOutTradeNo(2).substr(-8, 8);
    par.url = '127.0.0.1';
    par.sign = partnerSign('mctCe4YWfMpPzAYv', par);
    wxPay(par, res);
}
router.post('/llcPay', paymentRouter.llcPay);

/**
 * 积分商城抵用积分购买  (自定义)
 * @param   price
 * @param   token
 * @param   app_sid
 * @param   pay_type     wxpay   alipay
 *          url/payment/customScoreBuy
 */
function getShopScoreOrderCode(uid) {
    var now = new Date();
    var code ='' + uid + now.getFullYear() + parseInt(now.getMonth() + 1) + now.getDate() + now.getHours() + now.getMinutes() + Math.floor(Math.random()*10) + Math.floor(Math.random()*10) + now.getSeconds();
    code = code + '0712';
    return code;
}
function alipayToCustomOrder(data, res) {
    var AlipayConfig = require('../db/alipay_config.json').alipay_usuz_cfg;
    var alib = require('../libs/alipay_usuz/alipay.js');
    var out_trade_no = data.order_code;
    var subject = data.vip_name;
    var body = data.vip_name;
    var total_fee = data.pay_amount;
    var app_id = AlipayConfig.app_id;
    var method = "alipay.trade.precreate";
    var charset = AlipayConfig.input_charset;
    var sign_type = "RSA";
    var timestamp = moment().format("YYYY-MM-DD HH:mm:ss");
    var format = "json";
    var version = "1.0";
    var biz_content = {
        out_trade_no : out_trade_no,
        total_amount : total_fee,
        subject : subject,
        timeout_express : "10m",
        body : body
    };
    var sParaTemp = [];
    sParaTemp.push(["app_id", app_id]);
    sParaTemp.push(["method", method]);
    sParaTemp.push(["charset", charset]);
    sParaTemp.push(["sign_type", sign_type]);
    sParaTemp.push(["timestamp", timestamp]);
    sParaTemp.push(["format", format]);
    sParaTemp.push(["version", version]);
    sParaTemp.push(["notify_url", AlipayConfig.notify_url]);
    sParaTemp.push(["biz_content", JSON.stringify(biz_content)]);
    var sPara = alib.buildRequestPara2(sParaTemp);
    var path = AlipayConfig.ALIPAY_PATH;
    var sURL = alib.getPath(path, sPara);
    request({
        url: AlipayConfig.ali_host + sURL,
        method: 'GET',
        headers: {
            'charset': 'utf-8'
        }
    },function(error, response, body){
        console.log("支付宝返回内容:\n", body);
        body = JSON.parse(body);
        var result = alib.checkRSA(body.alipay_trade_precreate_response, body.sign);
        var response = body.alipay_trade_precreate_response;
        if(response.code !== "10000") return res.json(new ERR('订单错误请重试！', 400));
        var qr_img = 'http://qr.liantu.com/api.php?&w=200&text='+response.qr_code;
        res.json(new PKG({qr_img: qr_img, order_code: out_trade_no}));
    });
}
function wxpayToCustomOrder(data, res) {
    var input = new PayData.WxPayDataBase();
    var ip = '127.0.0.1';
    var out_trade_no = data.order_code;
    var total_fee = parseInt(data.pay_amount * 100);
    var body = data.vip_name;
    var qrUrl = '';
    var payApi = new API.WxPayApi();
    input.SetBody(body);
    input.SetAttach(data.vip_name);
    input.SetOut_trade_no(out_trade_no);
    input.SetTotal_fee(total_fee);
    input.SetSpbill_create_ip(ip);
    input.SetTrade_type("NATIVE");
    input.SetProduct_id(data.vip_name);
    input.SetKeys();
    payApi.unifiedOrder(input, 6, null, ip, function(result){
        if(result) {
            result = input.Init(result);
            qrUrl = result['code_url'];
            console.log(result);
            res.json(new PKG({qrUrl:qrUrl, order_code: out_trade_no}));
        } else {
            res.json(new ERR('订单错误请重试！', 400));
        }

    });
}
paymentRouter.customScoreBuy = function (req, res) {
    var par = req.body;
    var orderInfo = {};
    if(!par.price || parseFloat(par.price) < 0.01) return res.json(new ERR('充值金额过小，请调整金额！', 400));
    if(!par.app_sid) return  res.json(new ERR('应用类型不能为空', 400));
    if(!par.pay_type) return res.json(new ERR('支付类型不能为空', 400));
    if(par.pay_type != 'alipay' && par.pay_type != 'wxpay') return res.json(new ERR('暂无该类型支付方式', 400));
    UserToken.checkLogin(par.token, function(err, userInfo){
        if(err) return res.json(new ERR(err, 400));
        if(!userInfo) return res.json(new ERR('请先登录', 403));
        orderInfo.order_code = getShopScoreOrderCode(userInfo.uid);
        orderInfo.uid = userInfo.uid;
        orderInfo.price = par.price;
        orderInfo.created_time = new Date();
        orderInfo.end_time = '2040-08-08';
        orderInfo.item_id = 0;
        orderInfo.app_sid = par.app_sid;
        orderInfo.vip_sid = 'jf_shop_score';
        orderInfo.vip_name = parseFloat(par.price) * 100 + '抵用分';
        orderInfo.vip_type = 1;
        orderInfo.vip_lvl = parseFloat(par.price) * 100;
        orderInfo.vip_duration = 0;
        orderInfo.vip_expire = 0;
        orderInfo.num = 1;
        orderInfo.discount = 1;
        orderInfo.pay_amount = par.price;
        orderInfo.commission1 = 0;
        orderInfo.commission2 = 0;
        orderInfo.score = 0;
        orderInfo.status = 12;
        paymentDao.createCustomOrder(orderInfo, function(err, data) {
            if(err) return res.json(new ERR(err, 400));
            if(par.pay_type == 'alipay') alipayToCustomOrder(data, res);
            if(par.pay_type == 'wxpay') wxpayToCustomOrder(data, res);
        })
    });
}
router.post('/customScoreBuy', paymentRouter.customScoreBuy);

module.exports = router;